package com.sinosoft.builder.config;

import java.io.File;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.codehaus.plexus.velocity.VelocityComponent;

import com.sinosoft.builder.generator.GeneratorException;
import com.sinosoft.builder.parser.SinoParserType;

/**
 * 解析builder配置文件，用于组件创建过程
 * 
 * @author 潘巍（Peter Pan）
 * @since 2010-5-6 上午09:22:31
 */
public class BuilderConfig implements ILoaderHolder {

	public static final String VM_ENCODING = "utf-8";

	private ClassLoader _loader;

	private Logger _log;

	private String tempDir = "META-INF/templates";

	private File destDir;

	private File resDir;

	private List<Object> resObjects;

	private VelocityComponent velocity;

	/**
	 * @param loader
	 * @param log
	 */
	public BuilderConfig(ClassLoader loader, Logger log) {
		_loader = loader;
		_log = log;
	}

	/**
	 * 
	 * @param loader
	 * @param log
	 * @param destDir
	 * @param resDir
	 * @param tempDir
	 * @throws ParsingException
	 */
	public BuilderConfig(ClassLoader loader, Logger log, File destDir,
			File resDir, VelocityComponent velocity, SinoParserType type)
			throws ParsingException {
		this(loader, log);
		this.destDir = destDir;
		this.resDir = new File(resDir, type.getXmlFileNameOrPath());
		this.velocity = velocity;

		// 初始化资源文件集合
		resObjects = type.parser();
	}

	@Override
	public ClassLoader getLoader() {
		return _loader;
	}

	@Override
	public void setLoader(ClassLoader loader) {
		_loader = loader;
	}

	@Override
	public Logger getLog() {
		return _log;
	}

	@Override
	public Template getTemplate(String name) throws GeneratorException {
		String fileName = this.tempDir + "/" + name;
		try {
			return this.velocity.getEngine().getTemplate(fileName, VM_ENCODING);
		} catch (ResourceNotFoundException e) {
			_log.error("获得模板文件（" + name + "）出现异常: ", e);
			throw new GeneratorException(e);
		} catch (ParseErrorException e) {
			_log.error("获得模板文件（" + name + "）出现异常: ", e);
			throw new GeneratorException(e);
		} catch (Exception e) {
			_log.error("获得模板文件（" + name + "）出现异常: ", e);
			throw new GeneratorException(e);
		}
	}

	@Override
	public void setDestDir(File f) {
		this.destDir = f;
	}

	@Override
	public void setResDir(File f) {
		this.resDir = f;
	}

	@Override
	public File getDestDir() {
		return this.destDir;
	}

	@Override
	public File getResDir() {
		return this.resDir;
	}

	@Override
	public List<Object> getResObjects() {
		return resObjects;
	}

}
